package com.uzai.console.service.wechatwork.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.uzai.common.entity.User;
import com.uzai.common.entity.WxworkUser;
import com.uzai.common.entity.WechatUser;
import com.uzai.common.entity.WxworkUser;
import com.uzai.common.enums.*;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.msg.MsgDto;
import com.uzai.common.msg.NoticeMsgDto;
import com.uzai.common.result.ResponseCode;
import com.uzai.common.utils.EsIndexName;
import com.uzai.console.common.UzaiRespVo;
import com.uzai.console.common.utils.*;
import com.uzai.console.constant.CacheKey;
import com.uzai.console.constant.Const;
import com.uzai.console.constant.ES.ESConstant;
import com.uzai.console.constant.ES.ESResult;
import com.uzai.console.constant.ES.ElasticsearchUtilGroupMsg;
import com.uzai.console.dto.feign.groupsendjob.GroupSendChildidPushDto;
import com.uzai.console.dto.feign.groupsendjob.NewGroupSendMsgDto;
import com.uzai.console.dto.feign.wxcontacts.WxContactsRegisterDto;
import com.uzai.console.dto.groupsendjob.GroupSendJobConditionOrderDto;
import com.uzai.console.dto.groupsendjob.GroupSendJobUserQueryParaDto;
import com.uzai.console.dto.rocketmq.friendrequest.DeleteUserDto;
import com.uzai.console.dto.rocketmq.groupsendjob.GroupSendMsgDto;
import com.uzai.console.dto.user.wechatuser.WechatUserQuery;
import com.uzai.console.dto.user.wxworkuser.WxworkUserQuery;
import com.uzai.console.dto.wechatprivate.wxcontacts.NewBatchSendMessageTaskDto;
import com.uzai.console.dto.wechatprivate.wxcontacts.WxContactsQuery;
import com.uzai.console.dto.wechatwork.wxworkcontacts.*;
import com.uzai.console.entity.DeviceWxworkInfo;
import com.uzai.console.entity.GroupSendJob;
import com.uzai.console.entity.WxqContactRefresh;
import com.uzai.console.entity.es.EsWorkWxContacts;
import com.uzai.console.entity.es.EsWxContacts;
import com.uzai.console.enums.GroupSendJobSourceEnum;
import com.uzai.console.mapper.*;
import com.uzai.console.service.device.DeviceService;
import com.uzai.console.service.feign.UzaiBroadcastFeignService;
import com.uzai.console.service.feign.WxContactsFeignService;
import com.uzai.console.service.groupsendjob.GroupSendJobConditionService;
import com.uzai.console.service.merchant.MerchantService;
import com.uzai.console.service.rocketmq.NoticeMsgPushProducerService;
import com.uzai.console.service.user.UserService;
import com.uzai.console.service.wechatwork.WxworkContactsService;
import com.uzai.console.vo.device.DeviceInfoSimpleVo;
import com.uzai.console.vo.exportinfo.ExportAmountVo;
import com.uzai.console.vo.wechatprivate.wxcontacts.WxContactsBatchRefreshVo;
import com.uzai.console.vo.wechatwork.wxworkcontacts.WxworkContactsVo;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.reindex.DeleteByQueryRequest;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 企业微信-微信通讯录
 * @author liuqi
 * @date 2021年08月13日 11:34
 */
@Service
public class WxworkContactsServiceImpl implements WxworkContactsService {

    Logger logger = LoggerFactory.getLogger(WxworkContactsServiceImpl.class);

    @Autowired
    private ElasticsearchUtilGroupMsg elasticsearchUtilGroupMsg;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private NoticeMsgPushProducerService noticeMsgPushProducerService;
    @Autowired
    private WxContactsFeignService wxContactsFeignService;
    @Autowired
    private DeviceWxworkInfoMapper deviceWxworkInfoMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private GroupSendJobMapper groupSendJobMapper;
    @Autowired
    private UserService userService;
    @Autowired
    private UzaiBroadcastFeignService uzaiBroadcastFeignService;
    @Autowired
    private PyqExpressionMapper pyqExpressionMapper;
    @Autowired
    private SysConfigMapper sysConfigMapper;
    @Autowired
    private MerchantService merchantService;
    @Autowired
    private GroupSendJobConditionService groupSendJobConditionService;
    @Autowired
    private WxworkUserMapper wxworkUserMapper;
    @Autowired
    private WxqContactRefreshMapper wxqContactRefreshMapper;

    /**
     * 查询微信通讯录列表
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxworkContactsQuery
     * @param tuominFlag 是否需要脱敏
     * @return null
     */
    public Page<WxworkContactsVo> findWxworkContactsList(WxworkContactsQuery wxworkContactsQuery, Boolean tuominFlag){
        //新建返回到页面的LIST对象
        List<WxworkContactsVo> wxworkContactsVoList = new ArrayList<>();

        //执行分页查询对象
        Page<WxworkContactsVo> page = new Page<>();
        wxworkContactsQuery.convert(page);

        //ES查询
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQuery_and = QueryBuilders.boolQuery();
        BoolQueryBuilder boolQuery_or = QueryBuilders.boolQuery();

        //运营商ID
        boolQuery_and.must(QueryBuilders.termQuery("merId", Tools.getLong(wxworkContactsQuery.getMerId())));

        //性别
        if(wxworkContactsQuery.getGender() != null){
            boolQuery_and.must(QueryBuilders.termQuery("gender", wxworkContactsQuery.getGender()));
        }

        //高亮字段
        String highlightField = null;

        //微信昵称
        if(StringUtils.isNotBlank(wxworkContactsQuery.getUserName())){
            //boolQuery_or.should(QueryBuilders.matchQuery("userName", wxworkContactsQuery.getUserName()));
            //boolQuery_or.should(QueryBuilders.termQuery("userName.raw", wxworkContactsQuery.getUserName()));

            //支持中文分词
            boolQuery_or.should(QueryBuilders.matchQuery("userName", wxworkContactsQuery.getUserName()));

            //支持数字和英文
            boolQuery_or.should(QueryBuilders.wildcardQuery("userName", "*"+wxworkContactsQuery.getUserName() +"*"));

            //highlightField = "userName";
        }

        //微信id
        if(StringUtils.isNotBlank(wxworkContactsQuery.getWxid())){
            boolQuery_and.must(QueryBuilders.termQuery("wxid",wxworkContactsQuery.getWxid()));
            //highlightField = "wxid";
        }

        //机器人唯一ID
        if(wxworkContactsQuery.getDeviceUniqueId() != null){
            boolQuery_and.must(QueryBuilders.termQuery("deviceUniqueId",wxworkContactsQuery.getDeviceUniqueId()));
        }

        //机器人唯一id列表
        if(wxworkContactsQuery.getDeviceUniqueIdList() != null && wxworkContactsQuery.getDeviceUniqueIdList().size() > 0){
            boolQuery_and.must(QueryBuilders.termsQuery("deviceUniqueId", wxworkContactsQuery.getDeviceUniqueIdList()));
        }

        //备注
        if(StringUtils.isNotBlank(wxworkContactsQuery.getRemark())){
            //boolQuery_and.must(QueryBuilders.matchPhraseQuery("remark", wxworkContactsQuery.getRemark()));

            //支持中文分词
            boolQuery_or.should(QueryBuilders.matchQuery("remark", wxworkContactsQuery.getRemark()));
            //支持数字和英文
            boolQuery_or.should(QueryBuilders.wildcardQuery("remark", "*"+wxworkContactsQuery.getRemark() +"*"));

        }

        //子账号绑定机器人
        List<Long> subDeviceUniqueIdList = wxworkContactsQuery.getSubDeviceUniqueIdList();
        if(subDeviceUniqueIdList != null && subDeviceUniqueIdList.size() > 0){
            for (Long deviceUniqueId : subDeviceUniqueIdList) {
                boolQuery_or.should(QueryBuilders.termQuery("deviceUniqueId", deviceUniqueId));
            }
        }

        //最后群发消息开始时间
        if(wxworkContactsQuery.getLastGroupSendTimeStart() != null){
            boolQuery_and.must(QueryBuilders.rangeQuery("lastGroupSendTime").gte(wxworkContactsQuery.getLastGroupSendTimeStart()));
        }

        //最后群发消息结束时间
        if(wxworkContactsQuery.getLastGroupSendTimeEnd() != null){
            boolQuery_and.must(QueryBuilders.rangeQuery("lastGroupSendTime").lte(wxworkContactsQuery.getLastGroupSendTimeEnd()));
        }

        //免骚扰时间(针对群发消息用户过滤，这个时间发以后已经群发消息的用户不查询出来)
        if(wxworkContactsQuery.getBusyGroupSendMsgTime() != null){
            boolQuery_and.must(QueryBuilders.rangeQuery("lastGroupSendTime").lt(wxworkContactsQuery.getBusyGroupSendMsgTime()));
        }

        //备注列表(匹配任何一个都算)
        List<String> remarkList = wxworkContactsQuery.getRemarkList();
        if(remarkList != null && remarkList.size() > 0){
            for (String remark : remarkList) {
                boolQuery_or.should(QueryBuilders.matchPhraseQuery("remark", remark));
            }
        }

        searchSourceBuilder.query(boolQuery_and.must(boolQuery_or));

        //判断是否需要脱敏
        if(tuominFlag == null){
            tuominFlag = false;
        }
        String cmstype_wxcontacts_wxid_verified =  (String)redisTemplate.opsForValue().get(String.format(Const.SmsType.CMSTYPE_WXCONTACTS_WXID_VERIFIED, wxworkContactsQuery.getMerId()));
        if(StringUtils.isNotBlank(cmstype_wxcontacts_wxid_verified)){
            tuominFlag = false;
        }

        String uzai_workwx_contacts = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WORKWX_CONTACTS, wxworkContactsQuery.getMerId());
        ESResult esResult = elasticsearchUtilGroupMsg.searchListData(uzai_workwx_contacts, searchSourceBuilder, wxworkContactsQuery.getSize(), wxworkContactsQuery.getFromIndex(), null, null, highlightField, wxworkContactsQuery.getMerId());
        page.setTotal(esResult.getTotalHits());
        List<Map<String, Object>> dataList = esResult.getDataList();
        if(dataList != null && dataList.size() > 0){
            for (Map<String, Object> dataMp :dataList) {
                WxworkContactsVo wxworkContactsVo  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp)), WxworkContactsVo.class);

                //查询机器人信息
                DeviceWxworkInfo deviceWxworkInfo = deviceWxworkInfoMapper.selectById(wxworkContactsVo.getDeviceUniqueId(), wxworkContactsVo.getMerId());
                if(deviceWxworkInfo != null){
                    wxworkContactsVo.setDeviceName(deviceWxworkInfo.getDeviceName());
                    wxworkContactsVo.setDeviceRemark(deviceWxworkInfo.getDeviceRemark());
                }

                //会员信息
                if(StringUtils.isNotBlank(wxworkContactsVo.getWxid())){
                    User user = userService.findUserInfoByWxid(wxworkContactsVo.getMerId(), wxworkContactsVo.getWxid(), DeviceTypeEnum.DT_WORK_WECHAT.getKey());
                    if(user != null){
                        wxworkContactsVo.setUserId(user.getId());
                        wxworkContactsVo.setBalance(user.getBalance());
                        wxworkContactsVo.setIntegral(user.getIntegral());
                    }
                }

                //是否脱敏处理
                if(tuominFlag){
                    wxworkContactsVo.setWxid(DesensitizeUtil.around(Tools.getStr(wxworkContactsVo.getWxid()),3,3));
                }

                wxworkContactsVoList.add(wxworkContactsVo);
            }
        }

        //返回到页面分页对象
        page.setRecords(wxworkContactsVoList);
        //将分页信息复制到返回到页面的分页MO当中
        return page;
    }

    /**
     * 查询微信通讯录列表
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxworkContactsQuery
     * @return null
     */
    private Page<EsWorkWxContacts> findWxworkContactsListForGroupSendMsg(WxworkContactsQuery wxworkContactsQuery){
        //新建返回到页面的LIST对象
        List<EsWorkWxContacts> wxworkContactsVoList = new ArrayList<>();

        //执行分页查询对象
        Page<EsWorkWxContacts> page = new Page<>();
        wxworkContactsQuery.convert(page);

        //ES查询
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQuery_and = QueryBuilders.boolQuery();
        BoolQueryBuilder boolQuery_or = QueryBuilders.boolQuery();

        //运营商ID
        boolQuery_and.must(QueryBuilders.termQuery("merId", Tools.getLong(wxworkContactsQuery.getMerId())));

        //性别
        if(wxworkContactsQuery.getGender() != null){
            boolQuery_and.must(QueryBuilders.termQuery("gender", wxworkContactsQuery.getGender()));
        }

        //高亮字段
        String highlightField = null;

        //微信昵称
        if(StringUtils.isNotBlank(wxworkContactsQuery.getUserName())){
            boolQuery_or.should(QueryBuilders.matchQuery("userName", wxworkContactsQuery.getUserName()));
            boolQuery_or.should(QueryBuilders.termQuery("userName.raw", wxworkContactsQuery.getUserName()));
            highlightField = "userName";
        }

        //微信id
        if(StringUtils.isNotBlank(wxworkContactsQuery.getWxid())){
            boolQuery_and.must(QueryBuilders.termQuery("wxid",wxworkContactsQuery.getWxid()));
            //highlightField = "wxid";
        }

        //机器人唯一ID
        if(wxworkContactsQuery.getDeviceUniqueId() != null){
            boolQuery_and.must(QueryBuilders.termQuery("deviceUniqueId",wxworkContactsQuery.getDeviceUniqueId()));
        }

        //机器人唯一id列表
        if(wxworkContactsQuery.getDeviceUniqueIdList() != null && wxworkContactsQuery.getDeviceUniqueIdList().size() > 0){
            boolQuery_and.must(QueryBuilders.termsQuery("deviceUniqueId", wxworkContactsQuery.getDeviceUniqueIdList()));
        }

        //子账号绑定机器人
        List<Long> subDeviceUniqueIdList = wxworkContactsQuery.getSubDeviceUniqueIdList();
        if(subDeviceUniqueIdList != null && subDeviceUniqueIdList.size() > 0){
            for (Long deviceUniqueId : subDeviceUniqueIdList) {
                boolQuery_or.should(QueryBuilders.termQuery("deviceUniqueId", deviceUniqueId));
            }
        }

        //最后群发消息开始时间
        if(wxworkContactsQuery.getLastGroupSendTimeStart() != null){
            boolQuery_and.must(QueryBuilders.rangeQuery("lastGroupSendTime").gte(wxworkContactsQuery.getLastGroupSendTimeStart()));
        }

        //最后群发消息结束时间
        if(wxworkContactsQuery.getLastGroupSendTimeEnd() != null){
            boolQuery_and.must(QueryBuilders.rangeQuery("lastGroupSendTime").lte(wxworkContactsQuery.getLastGroupSendTimeEnd()));
        }

        //免骚扰时间(针对群发消息用户过滤，这个时间发以后已经群发消息的用户不查询出来)
        if(wxworkContactsQuery.getBusyGroupSendMsgTime() != null){
            boolQuery_and.must(QueryBuilders.rangeQuery("lastGroupSendTime").lt(wxworkContactsQuery.getBusyGroupSendMsgTime()));
        }

        searchSourceBuilder.query(boolQuery_and.must(boolQuery_or));

        String uzai_workwx_contacts = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WORKWX_CONTACTS, wxworkContactsQuery.getMerId());
        ESResult esResult = elasticsearchUtilGroupMsg.searchListData(uzai_workwx_contacts, searchSourceBuilder, wxworkContactsQuery.getSize(), wxworkContactsQuery.getFromIndex(), null, null, highlightField, wxworkContactsQuery.getMerId());
        page.setTotal(esResult.getTotalHits());
        List<Map<String, Object>> dataList = esResult.getDataList();
        if(dataList != null && dataList.size() > 0){
            for (Map<String, Object> dataMp :dataList) {
                EsWorkWxContacts esWorkWxContacts  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp)), EsWorkWxContacts.class);
                wxworkContactsVoList.add(esWorkWxContacts);
            }
        }

        //返回到页面分页对象
        page.setRecords(wxworkContactsVoList);
        //将分页信息复制到返回到页面的分页MO当中
        return page;
    }

    /**
     * 删除通讯录
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxworkContactsIdListDto
     * @return null
     */
    @Transactional
    public void deleteWxworkContacts(WxworkContactsIdListDto wxworkContactsIdListDto){

        List<String> idList = wxworkContactsIdListDto.getIdList();

        if(idList == null | idList.size() == 0){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入id");
        }

        String uzai_workwx_contacts = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WORKWX_CONTACTS, wxworkContactsIdListDto.getMerId());


        for (String id : idList){
            //查询微信通讯录
            Map<String,Object> dataMp = elasticsearchUtilGroupMsg.searchDataById(uzai_workwx_contacts, id, null);
            WxworkContactsVo wxworkContactsVo  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp)), WxworkContactsVo.class);
            if(wxworkContactsVo != null){
                //删除通讯录
                elasticsearchUtilGroupMsg.deleteDataById(uzai_workwx_contacts, id);

                //发送MQ消息
                MsgDto<DeleteUserDto> msgDto = new MsgDto<>();
                DeleteUserDto deleteUserDto = new DeleteUserDto();
                deleteUserDto.setWxid(wxworkContactsVo.getWxid());
                msgDto.setContent(deleteUserDto);
                msgDto.setId(IdWorker.getId());
                msgDto.setDeviceType(wxworkContactsVo.getDeviceType());
                msgDto.setDeviceUniqueId(wxworkContactsVo.getDeviceUniqueId());
                msgDto.setMerId(wxworkContactsVo.getMerId());
                msgDto.setMsgType(MessageFuncEnum.DELETE_USER.getValue());
                noticeMsgPushProducerService.deleteUser(msgDto);
            }
        }

        try {
            //解决ES延时删除
            Thread.sleep(1000);
        }catch (Exception e){

        }



    }

    /**
     * 单个发送消息
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxworkContactsSendMessageDto
     * @return null
     */
    public void sendMessage(WxworkContactsSendMessageDto wxworkContactsSendMessageDto){

        if(StringUtils.isBlank(wxworkContactsSendMessageDto.getId())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入主键id");
        }

        if(StringUtils.isBlank(wxworkContactsSendMessageDto.getMessage())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入消息内容");
        }

        String uzai_workwx_contacts = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WORKWX_CONTACTS, wxworkContactsSendMessageDto.getMerId());

        try {
            //查询微信通讯录
            Map<String, Object> dataMp = elasticsearchUtilGroupMsg.searchDataById(uzai_workwx_contacts, wxworkContactsSendMessageDto.getId(), null);
            WxworkContactsVo wxworkContactsVo = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp)), WxworkContactsVo.class);
            if (wxworkContactsVo != null) {
                //发送MQ消息
                MsgDto<NoticeMsgDto>  msgDto = new MsgDto<>();
                NoticeMsgDto  noticeMsgDto = new NoticeMsgDto();
                noticeMsgDto.setBizUserId(wxworkContactsVo.getWxid());
                String msg = Tools.getStr(wxworkContactsSendMessageDto.getMessage());
                noticeMsgDto.setContent(msg.replace("[昵称]", wxworkContactsVo.getUserName()));
                noticeMsgDto.setContentType(MessageTypeEnum.MT_TEXT.getValue());
                noticeMsgDto.setGroupId(null);
                noticeMsgDto.setNickName(wxworkContactsVo.getUserName());
                noticeMsgDto.setMsgSource(1);
                noticeMsgDto.setMsgBizType(KefuSendMsgEnum.UNSOLICITEDMSG.getKey());
                msgDto.setContent(noticeMsgDto);
                msgDto.setId(IdWorker.getId());
                msgDto.setDeviceType(wxworkContactsVo.getDeviceType());
                msgDto.setDeviceUniqueId(wxworkContactsVo.getDeviceUniqueId());
                msgDto.setMerId(wxworkContactsVo.getMerId());
                msgDto.setMsgType(MessageFuncEnum.SEND_CHAT_MESSAGE.getValue());
                noticeMsgPushProducerService.sendMessage(msgDto);
            }
        }catch (Exception e){
            logger.error("向通讯录好友发送消息出现异常：{}"+ e.getMessage());
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "发送消息失败");
        }
    }

    /**
     * 通讯录注册
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxworkContactsIdDto
     * @return null
     */
    public void register(WxworkContactsIdDto wxworkContactsIdDto){

        if(StringUtils.isBlank(wxworkContactsIdDto.getId())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入主键id");
        }

        String uzai_workwx_contacts = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WORKWX_CONTACTS, wxworkContactsIdDto.getMerId());

        //查询微信通讯录
        Map<String, Object> dataMp = elasticsearchUtilGroupMsg.searchDataById(uzai_workwx_contacts, wxworkContactsIdDto.getId(), null);
        WxworkContactsVo wxworkContactsVo = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp)), WxworkContactsVo.class);
        if (wxworkContactsVo != null) {
            //会员信息
            if (StringUtils.isNotBlank(wxworkContactsVo.getWxid())) {
                User user = userService.findUserInfoByWxid(wxworkContactsVo.getMerId(), wxworkContactsVo.getWxid(), DeviceTypeEnum.DT_WORK_WECHAT.getKey());
                if (user == null) {//没有找到会员信息，才注册
                    DeviceWxworkInfo deviceWxworkInfo = deviceWxworkInfoMapper.selectById(wxworkContactsVo.getDeviceUniqueId(), wxworkContactsVo.getMerId());
                    if (deviceWxworkInfo != null) {
                        //调用注册接口
                        WxContactsRegisterDto wxContactsRegisterDto = new WxContactsRegisterDto();
                        wxContactsRegisterDto.setMerId(wxworkContactsVo.getMerId());
                        wxContactsRegisterDto.setDeviceId(wxworkContactsVo.getDeviceId());
                        wxContactsRegisterDto.setDeviceType(DeviceTypeEnum.DT_WORK_WECHAT_VALUE);
                        wxContactsRegisterDto.setDeviceUniqueId(wxworkContactsVo.getDeviceUniqueId());
                        wxContactsRegisterDto.setHeadImg(wxworkContactsVo.getHimg());
                        wxContactsRegisterDto.setNickName(wxworkContactsVo.getUserName());
                        wxContactsRegisterDto.setWxid(wxworkContactsVo.getWxid());
                        UzaiRespVo<Boolean> uzaiRespVo =  wxContactsFeignService.userreg2(wxContactsRegisterDto);
                        logger.info("---企业微信通讯录注册会员---para={}, result={}",JSONObject.toJSONString(wxContactsRegisterDto), JSONObject.toJSONString(uzaiRespVo));
                    }
                }
            }
        }
    }

    /**
     * 刷新通讯录
     * @author liuqi
     * @date 2021/8/13 11:38
     * @return null
     */
    public void refreshWxworkContacts(WxworkContactsRefreshDto wxworkContactsRefreshDto){

        if(wxworkContactsRefreshDto.getDeviceUniqueId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择机器人");
        }

        DeviceWxworkInfo deviceWxworkInfo = deviceWxworkInfoMapper.selectById(wxworkContactsRefreshDto.getDeviceUniqueId(), wxworkContactsRefreshDto.getMerId());

        if(deviceWxworkInfo == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "机器人不存在");
        }

        //测试服方便测试，抛弃5分钟限流
        if(wxworkContactsRefreshDto.getMerId() != 1547482020152213506L) {
            String val = (String) redisTemplate.opsForValue().get(String.format(CacheKey.WXWORKCONTACTS_REFRESH, wxworkContactsRefreshDto.getMerId(), wxworkContactsRefreshDto.getDeviceUniqueId()));
            if (StringUtils.isNotBlank(val)) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "5分钟只允许同一个机器人请求一次");
            }
        }

        //往reids插入本次下载，允许5分钟请求一次，避免频繁提交
        redisTemplate.opsForValue().set(String.format(CacheKey.WXWORKCONTACTS_REFRESH, wxworkContactsRefreshDto.getMerId(), wxworkContactsRefreshDto.getDeviceUniqueId()),wxworkContactsRefreshDto.getDeviceUniqueId()+"",5, TimeUnit.MINUTES);

        //发送MQ消息
        MsgDto<Object> msgDto = new MsgDto<>();
        msgDto.setContent(null);
        msgDto.setId(IdWorker.getId());
        msgDto.setDeviceType(DeviceTypeEnum.DT_WORK_WECHAT_VALUE);
        msgDto.setDeviceUniqueId(wxworkContactsRefreshDto.getDeviceUniqueId());
        msgDto.setMerId(wxworkContactsRefreshDto.getMerId());
        msgDto.setMsgType(MessageFuncEnum.GET_MAIL_LIST_REQ.getValue());
        noticeMsgPushProducerService.updateWxContacts(msgDto);

        //保存更新通讯录时间
        deviceWxworkInfoMapper.updateRefreshWxcontactsTime(deviceWxworkInfo.getId(), DateUtil.getNowTime());
    }


    /**
     * 批量刷新企业微信通讯录
     * @author liuqi
     * @date 2021/8/13 11:38
     * @return null
     */
    public WxContactsBatchRefreshVo batchRefreshWxworkContacts(WxworkContactsBatchRefreshDto wxworkContactsBatchRefreshDto){

        WxContactsBatchRefreshVo wxContactsBatchRefreshVo = new WxContactsBatchRefreshVo();
        List<DeviceInfoSimpleVo> deviceInfoSimpleVoList = new ArrayList<>();
        wxContactsBatchRefreshVo.setErrorList(deviceInfoSimpleVoList);

        List<Long> deviceUniqueIdList = wxworkContactsBatchRefreshDto.getDeviceUniqueIdList();
        if(deviceUniqueIdList == null || deviceUniqueIdList.size() == 0){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择机器人");
        }

        if(wxworkContactsBatchRefreshDto.getType() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择刷新类型");
        }

        int now = DateUtil.getNowTime();

        for (Long deviceUniqueId : deviceUniqueIdList) {
            DeviceWxworkInfo deviceWxworkInfo = deviceWxworkInfoMapper.selectById(deviceUniqueId, wxworkContactsBatchRefreshDto.getMerId());
            if(deviceWxworkInfo != null){

                //查询此机器人是否存在列表中
                WxqContactRefresh wxqContactRefresh_old = wxqContactRefreshMapper.selectByDeviceId(deviceWxworkInfo.getDeviceId());
                if(wxqContactRefresh_old == null || wxqContactRefresh_old.getStatus() == 2){//为空或者状态为2，则新增加

                    //如果存在且完成状态，且先删除，在添加
                    if(wxqContactRefresh_old != null){
                        wxqContactRefreshMapper.deleteById(wxqContactRefresh_old.getId(), wxqContactRefresh_old.getMerId());
                    }

                    WxqContactRefresh wxqContactRefresh = new WxqContactRefresh();
                    wxqContactRefresh.setId(IdWorker.getId());
                    wxqContactRefresh.setMerId(wxworkContactsBatchRefreshDto.getMerId());
                    wxqContactRefresh.setType(wxworkContactsBatchRefreshDto.getType());
                    wxqContactRefresh.setDeviceType(DeviceTypeEnum.DT_WORK_WECHAT.getKey());
                    wxqContactRefresh.setDeviceUniqueId(deviceUniqueId);
                    wxqContactRefresh.setDeviceId(deviceWxworkInfo.getDeviceId());
                    wxqContactRefresh.setStatus(0); //未开始
                    wxqContactRefresh.setSendTime(0);
                    wxqContactRefresh.setCreateTime(now);
                    wxqContactRefresh.setUpdateTime(now);
                    wxqContactRefreshMapper.insert(wxqContactRefresh);
                }else{ //存在不允许添加,返回给前端页面
                    DeviceInfoSimpleVo deviceInfoSimpleVo = new DeviceInfoSimpleVo();
                    BeanUtils.copyProperties(deviceWxworkInfo, deviceInfoSimpleVo);
                    deviceInfoSimpleVoList.add(deviceInfoSimpleVo);
                }

//
//
//                //发送MQ消息
//                MsgDto<Object> msgDto = new MsgDto<>();
//                msgDto.setContent(null);
//                msgDto.setId(IdWorker.getId());
//                msgDto.setDeviceType(DeviceTypeEnum.DT_WORK_WECHAT_VALUE);
//                msgDto.setDeviceUniqueId(deviceUniqueId);
//                msgDto.setMerId(wxworkContactsBatchRefreshDto.getMerId());
//                msgDto.setMsgType(MessageFuncEnum.GET_MAIL_LIST_REQ.getValue());
//                noticeMsgPushProducerService.updateWxContacts(msgDto);
//
//                //保存更新通讯录时间
//                deviceWxworkInfoMapper.updateRefreshWxcontactsTime(deviceWxworkInfo.getId(), DateUtil.getNowTime());
            }
        }

        return wxContactsBatchRefreshVo;
    }


    /**
     * 根据单个机器人群发消息(异步)
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param wxworkAddBatchSendMessageTaskDto
     * @return null
     */
    @Async("taskExecutor")
    public void groupSendMsgByDeviceUniqueId(WxworkAddBatchSendMessageTaskDto wxworkAddBatchSendMessageTaskDto){
        WxworkContactsQuery wxworkContactsQuery = wxworkAddBatchSendMessageTaskDto.getWxworkContactsQuery();
        wxworkContactsQuery.setMerId(wxworkAddBatchSendMessageTaskDto.getMerId());
        GroupSendJob groupSendJobParent = wxworkAddBatchSendMessageTaskDto.getGroupSendJobParent();
        groupSendJobParent.setMerId(wxworkAddBatchSendMessageTaskDto.getMerId());
        if(wxworkContactsQuery == null){//判断条件是否为空
            logger.error("--groupSendMsgByDeviceUniqueId is error; wechatUserQuery is null");
            return;
        }
        if(wxworkContactsQuery.getDeviceUniqueId() == null){//判断机器人是否为空
            logger.error("--groupSendMsgByDeviceUniqueId is error; deviceUniqueId is null");
            return;
        }
        if(groupSendJobParent == null){//主线程不存在
            logger.error("--groupSendMsgByDeviceUniqueId is error; groupSendJobParent is null");
            return;
        }

        DeviceWxworkInfo deviceWxworkInfo = deviceWxworkInfoMapper.selectById(wxworkContactsQuery.getDeviceUniqueId(), wxworkAddBatchSendMessageTaskDto.getMerId());
        if(deviceWxworkInfo == null){
            logger.error("--groupSendMsgByDeviceUniqueId is error; deviceWechatInfo is null,  deviceUniqueId={}" + wxworkContactsQuery.getDeviceUniqueId());
            return;
        }

        //查询总用户数
        int pageCurrent = 1; //从第一页开始查询
        wxworkContactsQuery.setCurrent(pageCurrent);
        wxworkContactsQuery.setSize(20);

        Page<WxworkContactsVo> wxworkContactsVoPage = findWxworkContactsList(wxworkContactsQuery, false);
        if(wxworkContactsVoPage != null && wxworkContactsVoPage.getRecords() != null && wxworkContactsVoPage.getRecords().size() > 0){
            //添加群发消息子任务
            Integer now = DateUtil.getNowTime();
            //添加群发消息主任务
            GroupSendJob groupSendJob_son = new GroupSendJob();
            groupSendJob_son.setId(IdWorker.getId());
            groupSendJob_son.setParentId(groupSendJobParent.getId()); //主任务id
            groupSendJob_son.setMerId(wxworkAddBatchSendMessageTaskDto.getMerId());
            groupSendJob_son.setDeviceType(DeviceTypeEnum.DT_WORK_WECHAT.getKey());
            groupSendJob_son.setDeviceUniqueId(wxworkContactsQuery.getDeviceUniqueId());
            groupSendJob_son.setName(groupSendJobParent.getName());
            groupSendJob_son.setSource(GroupSendJobSourceEnum.PRIVATE_CONTACTS.getId());
            groupSendJob_son.setContent(groupSendJobParent.getContent());
            groupSendJob_son.setStatus(GroupSendStatusEnum.NOT_START.getValue());
            groupSendJob_son.setTotalCount((int)wxworkContactsVoPage.getTotal());
            groupSendJob_son.setFinishCount(0);
            groupSendJob_son.setTimeInterval(groupSendJobParent.getTimeInterval());
            groupSendJob_son.setBeginTime(groupSendJobParent.getBeginTime());
            groupSendJob_son.setExptime(groupSendJobParent.getExptime()); //当前时间之后的15天内
            groupSendJob_son.setUserLab(groupSendJobParent.getUserLab());
            groupSendJob_son.setUserRemark(groupSendJobParent.getUserRemark());
            groupSendJob_son.setNightTime(groupSendJobParent.getNightTime());
            groupSendJob_son.setCreateTime(now);
            groupSendJob_son.setUpdateTime(now);
            groupSendJobMapper.insertSelective(groupSendJob_son);

            try{
                //线程睡眠0.5秒
                Thread.sleep(500);
            } catch (Exception e){

            }

            //分页查询数据
            //延迟时间
            int delay = 0;//循环累加延迟时间
            while(wxworkContactsVoPage != null && wxworkContactsVoPage.getRecords() != null && wxworkContactsVoPage.getRecords().size() > 0){
                //发送消息
                for(WxworkContactsVo wxworkContactsVo : wxworkContactsVoPage.getRecords()){
                    //发送MQ消息
                    GroupSendMsgDto groupSendMsgDto = new GroupSendMsgDto();
                    groupSendMsgDto.setParentJobId(groupSendJob_son.getParentId());
                    groupSendMsgDto.setChildJobId(groupSendJob_son.getId());
                    String msg = Tools.getStr(groupSendJob_son.getContent());
                    groupSendMsgDto.setMsg(msg.replace("[昵称]", wxworkContactsVo.getUserName()));
                    groupSendMsgDto.setMerId(wxworkContactsVo.getMerId());
                    groupSendMsgDto.setDeviceUniqueId(wxworkContactsVo.getDeviceUniqueId());
                    groupSendMsgDto.setDeviceType(DeviceTypeEnum.DT_WORK_WECHAT_VALUE);
                    groupSendMsgDto.setMsgType(MessageTypeEnum.MT_TEXT.getValue());
                    groupSendMsgDto.setUserId(null);
                    groupSendMsgDto.setBizUserId(wxworkContactsVo.getWxid());
                    groupSendMsgDto.setNickName(wxworkContactsVo.getUserName());
                    groupSendMsgDto.setDelay(delay);
                    groupSendMsgDto.setOriginalDelay(delay);
                    delay = delay + groupSendJobParent.getTimeInterval(); //循环累加延迟时间
                    groupSendMsgDto.setRetry(0);
                    groupSendMsgDto.setLabel(groupSendJobParent.getUserLab());
                    String remark = Tools.getStr(groupSendJobParent.getUserRemark()).replace("[昵称]", wxworkContactsVo.getUserName());
                    groupSendMsgDto.setRemark(remark);
                    //群发消息
                    noticeMsgPushProducerService.groupSendMsg(groupSendMsgDto);

                }
                pageCurrent ++ ; //页面+1
                wxworkContactsQuery.setCurrent(pageCurrent); //修改页面
                wxworkContactsVoPage = findWxworkContactsList(wxworkContactsQuery, false);
            }
        }
    }

    /**
     * 批量注册
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param wxworkContactsQuery
     * @return null
     */
    @Async("taskExecutor")
    public void batchRegisterSync(WxworkContactsQuery wxworkContactsQuery){

        //查询机器人未到期
        int currentPage = 1; //当前页
        int size = 100;
        //查询总用户数
        wxworkContactsQuery.setSize(size);
        wxworkContactsQuery.setCurrent(currentPage);

        Page<WxworkContactsVo> wxworkContactsVoPage = findWxworkContactsList(wxworkContactsQuery, false);
        while(wxworkContactsVoPage != null && wxworkContactsVoPage.getRecords() != null && wxworkContactsVoPage.getRecords().size() > 0){
            //发送消息
            for(WxworkContactsVo wxworkContactsVo : wxworkContactsVoPage.getRecords()){
                try {
                    //会员信息
                    if(StringUtils.isNotBlank(wxworkContactsVo.getWxid())){
                        User user = userService.findUserInfoByWxid(wxworkContactsVo.getMerId(), wxworkContactsVo.getWxid(), DeviceTypeEnum.DT_WORK_WECHAT.getKey());
                        if(user == null){ //没有找到会员信息，才注册
                            DeviceWxworkInfo deviceWxworkInfo = deviceWxworkInfoMapper.selectById(wxworkContactsVo.getDeviceUniqueId(), wxworkContactsVo.getMerId());
                            if(deviceWxworkInfo != null){
                                //调用注册接口
                                WxContactsRegisterDto wxContactsRegisterDto = new WxContactsRegisterDto();
                                wxContactsRegisterDto.setMerId(wxworkContactsVo.getMerId());
                                wxContactsRegisterDto.setDeviceId(wxworkContactsVo.getDeviceId());
                                wxContactsRegisterDto.setDeviceType(DeviceTypeEnum.DT_WORK_WECHAT_VALUE);
                                wxContactsRegisterDto.setDeviceUniqueId(wxworkContactsVo.getDeviceUniqueId());
                                wxContactsRegisterDto.setHeadImg(wxworkContactsVo.getHimg());
                                wxContactsRegisterDto.setNickName(wxworkContactsVo.getUserName());
                                wxContactsRegisterDto.setWxid(wxworkContactsVo.getWxid());
                                UzaiRespVo<Boolean> uzaiRespVo =  wxContactsFeignService.userreg2(wxContactsRegisterDto);
                                logger.info("---查询结果批量注册通讯录会员---para={}, result={}",JSONObject.toJSONString(wxContactsRegisterDto), JSONObject.toJSONString(uzaiRespVo));
                            }
                        }
                    }
                }catch (Exception e){
                    logger.error("通讯录注册会员失败，error={}", e.getMessage());
                }
            }

            currentPage ++ ; //页码+1
            wxworkContactsQuery.setCurrent(currentPage);
            wxworkContactsVoPage = findWxworkContactsList(wxworkContactsQuery, false);
        }
    }

    /**
     * 查询微信通讯录总记录数
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxworkContactsQuery
     * @return null
     */
    public long searchTotal(WxworkContactsQuery wxworkContactsQuery){
        SearchSourceBuilder searchSourceBuilder =new SearchSourceBuilder();
        BoolQueryBuilder boolQuery_and = QueryBuilders.boolQuery();
        BoolQueryBuilder boolQuery_or = QueryBuilders.boolQuery();


        boolQuery_and.must(QueryBuilders.termQuery("merId",wxworkContactsQuery.getMerId()));

        //性别
        if(wxworkContactsQuery.getGender() != null){
            boolQuery_and.must(QueryBuilders.termQuery("gender", wxworkContactsQuery.getGender()));
        }

        //机器人唯一ID
        if(wxworkContactsQuery.getDeviceUniqueId() != null){
            boolQuery_and.must(QueryBuilders.termQuery("deviceUniqueId",wxworkContactsQuery.getDeviceUniqueId()));
        }

        //机器人唯一id列表
        if(wxworkContactsQuery.getDeviceUniqueIdList() != null && wxworkContactsQuery.getDeviceUniqueIdList().size() > 0){
            boolQuery_and.must(QueryBuilders.termsQuery("deviceUniqueId", wxworkContactsQuery.getDeviceUniqueIdList()));
        }

        //子账号绑定机器人
        List<Long> subDeviceUniqueIdList = wxworkContactsQuery.getSubDeviceUniqueIdList();
        if(subDeviceUniqueIdList != null && subDeviceUniqueIdList.size() > 0){
            for (Long deviceUniqueId : subDeviceUniqueIdList) {
                boolQuery_or.should(QueryBuilders.termQuery("deviceUniqueId", deviceUniqueId));
            }
        }

        //微信昵称
        if(StringUtils.isNotBlank(wxworkContactsQuery.getUserName())){
            boolQuery_or.should(QueryBuilders.matchQuery("userName", wxworkContactsQuery.getUserName()));
            boolQuery_or.should(QueryBuilders.termQuery("userName.raw", wxworkContactsQuery.getUserName()));
        }

        //微信id
        if(StringUtils.isNotBlank(wxworkContactsQuery.getWxid())){
            boolQuery_and.must(QueryBuilders.termQuery("wxid",wxworkContactsQuery.getWxid()));
        }


        //免骚扰时间(针对群发消息用户过滤，这个时间发以后已经群发消息的用户不查询出来)
        if(wxworkContactsQuery.getBusyGroupSendMsgTime() != null){
            boolQuery_and.must(QueryBuilders.rangeQuery("lastGroupSendTime").lt(wxworkContactsQuery.getBusyGroupSendMsgTime()));
        }

        //备注
        if(StringUtils.isNotBlank(wxworkContactsQuery.getRemark())){
            boolQuery_and.must(QueryBuilders.matchPhraseQuery("remark", wxworkContactsQuery.getRemark()));
        }

        //备注列表(匹配任何一个都算)
        List<String> remarkList = wxworkContactsQuery.getRemarkList();
        if(remarkList != null && remarkList.size() > 0){
            for (String remark : remarkList) {
                boolQuery_or.should(QueryBuilders.matchPhraseQuery("remark", remark));
            }
        }

        searchSourceBuilder.query(boolQuery_and.must(boolQuery_or));

        String uzai_workwx_contacts = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WORKWX_CONTACTS, wxworkContactsQuery.getMerId());

        //查询
        long total = elasticsearchUtilGroupMsg.searchTotal(uzai_workwx_contacts, searchSourceBuilder);

        return total;
    }

    /**
     * 查询微信通讯录所有记录
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxworkContactsQuery
     * @return null
     */
    public List<WxworkContactsVo> scrollSearchAll(WxworkContactsQuery wxworkContactsQuery){
        List<WxworkContactsVo> wxworkContactsVoList = new ArrayList<>();
        SearchSourceBuilder searchSourceBuilder =new SearchSourceBuilder();
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        BoolQueryBuilder boolQuery_and = QueryBuilders.boolQuery();
        BoolQueryBuilder boolQuery_or = QueryBuilders.boolQuery();

        //运营商
        boolQuery.must(QueryBuilders.termQuery("merId",wxworkContactsQuery.getMerId()));

        //性别
        if(wxworkContactsQuery.getGender() != null){
            boolQuery_and.must(QueryBuilders.termQuery("gender", wxworkContactsQuery.getGender()));
        }

        //机器人唯一ID
        if(wxworkContactsQuery.getDeviceUniqueId() != null){
            boolQuery_and.must(QueryBuilders.termQuery("deviceUniqueId",wxworkContactsQuery.getDeviceUniqueId()));
        }

        //机器人唯一id列表
        if(wxworkContactsQuery.getDeviceUniqueIdList() != null && wxworkContactsQuery.getDeviceUniqueIdList().size() > 0){
            boolQuery_and.must(QueryBuilders.termsQuery("deviceUniqueId", wxworkContactsQuery.getDeviceUniqueIdList()));
        }

        //子账号绑定机器人
        List<Long> subDeviceUniqueIdList = wxworkContactsQuery.getSubDeviceUniqueIdList();
        if(subDeviceUniqueIdList != null && subDeviceUniqueIdList.size() > 0){
            for (Long deviceUniqueId : subDeviceUniqueIdList) {
                boolQuery_or.should(QueryBuilders.termQuery("deviceUniqueId", deviceUniqueId));
            }
        }

        //微信昵称
        if(StringUtils.isNotBlank(wxworkContactsQuery.getUserName())){
            boolQuery_or.should(QueryBuilders.matchQuery("userName", wxworkContactsQuery.getUserName()));
            boolQuery_or.should(QueryBuilders.termQuery("userName.raw", wxworkContactsQuery.getUserName()));
        }

        //微信id
        if(StringUtils.isNotBlank(wxworkContactsQuery.getWxid())){
            boolQuery_and.must(QueryBuilders.termQuery("wxid",wxworkContactsQuery.getWxid()));
        }

        //免骚扰时间(针对群发消息用户过滤，这个时间发以后已经群发消息的用户不查询出来)
        if(wxworkContactsQuery.getBusyGroupSendMsgTime() != null){
            boolQuery_and.must(QueryBuilders.rangeQuery("lastGroupSendTime").lt(wxworkContactsQuery.getBusyGroupSendMsgTime()));
        }

        //备注
        if(StringUtils.isNotBlank(wxworkContactsQuery.getRemark())){
            boolQuery_and.must(QueryBuilders.matchPhraseQuery("remark", wxworkContactsQuery.getRemark()));
        }

        searchSourceBuilder.query(boolQuery_and.must(boolQuery_or));
        //查询
        String uzai_workwx_contacts = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WORKWX_CONTACTS, wxworkContactsQuery.getMerId());
        List<Map<String,Object>> dataList = elasticsearchUtilGroupMsg.scrollSearchAll(uzai_workwx_contacts, searchSourceBuilder);
        if(dataList != null && dataList.size() > 0) {
            for (Map<String, Object> dataMp : dataList) {
                WxworkContactsVo wxworkContactsVo = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp)), WxworkContactsVo.class);
                wxworkContactsVoList.add(wxworkContactsVo);
            }
        }
        return wxworkContactsVoList;
    }

    /**
     * 根据单个机器人新建群发消息
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param wxworkNewBatchSendMessageTaskDto
     * @return null
     */
    public Integer newBatchSendMessageTaskSync(WxworkNewBatchSendMessageTaskDto wxworkNewBatchSendMessageTaskDto, Long groupSendJobParentId, Long deviceUniqueId, String loginName){

        //记录发送消息总数
        int sendMsgTotal_real = 0;

        DeviceWxworkInfo deviceWxworkInfo = deviceWxworkInfoMapper.selectById(deviceUniqueId, wxworkNewBatchSendMessageTaskDto.getMerId());
        if(deviceWxworkInfo == null){
            logger.error("--newBatchSendMessageTaskByDeviceUniqueId is error; deviceWxworkInfo is null,  deviceUniqueId={}" + deviceUniqueId);
            return sendMsgTotal_real;
        }

        WxworkContactsQuery wxworkContactsQuery = new WxworkContactsQuery();
        wxworkContactsQuery.setMerId(wxworkNewBatchSendMessageTaskDto.getMerId());
        wxworkContactsQuery.setDeviceUniqueId(deviceUniqueId);//单个机器人
        wxworkContactsQuery.setSubDeviceUniqueIdList(wxworkNewBatchSendMessageTaskDto.getSubDeviceUniqueIdList());

        //免打扰时间
        Integer busyTimeInterval = wxworkNewBatchSendMessageTaskDto.getBusyTimeInterval();
        //页面设置了免打扰时间(页面填写的是天数)
        if(busyTimeInterval != null){
            //免骚扰时间(针对群发消息用户过滤，这个时间发以后已经群发消息的用户不查询出来)= 现在时间-页面设置的免打扰时间
            Integer busyGroupSendMsgTime = wxworkNewBatchSendMessageTaskDto.getBeginTime() - busyTimeInterval * 3600 ;
            wxworkContactsQuery.setBusyGroupSendMsgTime(busyGroupSendMsgTime);
        }

        //查询总用户数
        int pageCurrent = 1; //从第一页开始查询
        wxworkContactsQuery.setCurrent(pageCurrent);
        wxworkContactsQuery.setSize(20);

        Page<EsWorkWxContacts> esWorkWxContactsPage = findWxworkContactsListForGroupSendMsg(wxworkContactsQuery);
        if(esWorkWxContactsPage != null && esWorkWxContactsPage.getRecords() != null && esWorkWxContactsPage.getRecords().size() > 0){
            //预计发送总数
            int sendTotal_will = (int)esWorkWxContactsPage.getTotal();
            //添加群发消息子任务
            Integer now = DateUtil.getNowTime();
            //添加群发消息主任务
            GroupSendJob groupSendJob_son = new GroupSendJob();
            groupSendJob_son.setId(IdWorker.getId());
            groupSendJob_son.setParentId(groupSendJobParentId); //主任务id
            groupSendJob_son.setMerId(wxworkNewBatchSendMessageTaskDto.getMerId());
            groupSendJob_son.setDeviceType(DeviceTypeEnum.DT_WORK_WECHAT.getKey());
            groupSendJob_son.setDeviceUniqueId(wxworkContactsQuery.getDeviceUniqueId());
            String name = Tools.getStr(wxworkNewBatchSendMessageTaskDto.getName());
            name = name.replace("[机器人昵称]", Tools.getStr(deviceWxworkInfo.getDeviceName()))
                    .replace("[机器人备注]",Tools.getStr(deviceWxworkInfo.getDeviceRemark()))
                    .replace("[创建时间]", Tools.getDateFormat(new Date(), "yyMMdd"))
                    .replace("[创建账号]", Tools.getStr(loginName));
            groupSendJob_son.setName(name);
            groupSendJob_son.setSource(GroupSendJobSourceEnum.WORK_CONTACTS.getId());
            groupSendJob_son.setContent(wxworkNewBatchSendMessageTaskDto.getContent());
            groupSendJob_son.setStatus(GroupSendStatusEnum.INIT.getValue());
            groupSendJob_son.setTotalCount(0); //默认发送数量为0
            groupSendJob_son.setFinishCount(0);
            groupSendJob_son.setTimeIntervalMin(wxworkNewBatchSendMessageTaskDto.getTimeIntervalMin());
            groupSendJob_son.setTimeInterval(wxworkNewBatchSendMessageTaskDto.getTimeInterval());
            groupSendJob_son.setBeginTime(wxworkNewBatchSendMessageTaskDto.getBeginTime());
            groupSendJob_son.setEndTime(wxworkNewBatchSendMessageTaskDto.getEndTime());
            groupSendJob_son.setExptime(now + 15*24*3600); //当前时间之后的15天内
            groupSendJob_son.setUserRemark(wxworkNewBatchSendMessageTaskDto.getUserRemark());
            groupSendJob_son.setUserLab(Tools.getStrNull(JSONObject.toJSONString(wxworkNewBatchSendMessageTaskDto.getUserLabList())));
            groupSendJob_son.setCleanLab(wxworkNewBatchSendMessageTaskDto.getCleanLab());
            //会员标签
            groupSendJob_son.setUserTags(Tools.getStrNull(JSONObject.toJSONString(wxworkNewBatchSendMessageTaskDto.getUserTagsList())));
            groupSendJob_son.setNightTime(wxworkNewBatchSendMessageTaskDto.getNightTime());
            groupSendJob_son.setBusyTimeInterval(wxworkNewBatchSendMessageTaskDto.getBusyTimeInterval());
            groupSendJob_son.setIgnore(null);
            groupSendJob_son.setIgnoreName(Tools.getStrEmpty(JSONObject.toJSONString(wxworkNewBatchSendMessageTaskDto.getIgnoreNameList())));
            groupSendJob_son.setIgnoreRemark(Tools.getStrEmpty(JSONObject.toJSONString(wxworkNewBatchSendMessageTaskDto.getIgnoreRemarkList())));
            groupSendJob_son.setSendStartTime(wxworkNewBatchSendMessageTaskDto.getBeginTime());
            groupSendJob_son.setUserQueryPara(Tools.getStrNull(JSONObject.toJSONString(wxworkNewBatchSendMessageTaskDto.getGroupSendJobUserQueryParaDto())));
            groupSendJob_son.setParaQueryType(Tools.getInteger(wxworkNewBatchSendMessageTaskDto.getParaQueryType()));
            groupSendJob_son.setCreateTime(now);
            groupSendJob_son.setUpdateTime(now);
            groupSendJobMapper.insertSelective(groupSendJob_son);

            try {

                //是否有屏蔽昵称关键词
                boolean IgnoreNameListFlag = false;
                List<String> ignoreNameList = wxworkNewBatchSendMessageTaskDto.getIgnoreNameList();
                if(ignoreNameList != null && ignoreNameList.size() > 0){
                    IgnoreNameListFlag = true;
                }

                //是否有屏蔽备注关键词
                boolean IgnoreRemarkListFlag = false;
                List<String> ignoreRemarkList = wxworkNewBatchSendMessageTaskDto.getIgnoreRemarkList();
                if(ignoreRemarkList != null && ignoreRemarkList.size() > 0){
                    IgnoreRemarkListFlag = true;
                }

                //延迟时间
                int delay = 0;//循环累加延迟时间
                while(esWorkWxContactsPage != null && esWorkWxContactsPage.getRecords() != null && esWorkWxContactsPage.getRecords().size() > 0) {

                    //临时封装发送消息对象列表
                    List<NewGroupSendMsgDto> newGroupSendMsgDtoList = new ArrayList<>();
                    List<EsWorkWxContacts> esWorkWxContactsList = esWorkWxContactsPage.getRecords();

                    if(esWorkWxContactsList != null && esWorkWxContactsList.size() > 0){
                        //判断是否先需要匹配查询条件(1-发送前先筛选条件后创建任务)
                        if(Tools.getInteger(wxworkNewBatchSendMessageTaskDto.getParaQueryType()).intValue() == 1){
                            //条件查询过滤，返回符合条件的通讯录
                            esWorkWxContactsList = checkParaQuery(esWorkWxContactsList, wxworkNewBatchSendMessageTaskDto);
                        }

                        for (EsWorkWxContacts esWorkWxContacts : esWorkWxContactsList) {

                            //是否需要发送消息, 默认发送
                            boolean sendMsgFlag = true;

                            if(IgnoreNameListFlag) {//需要过滤昵称
                                String nick = Tools.getStr(esWorkWxContacts.getUserName());
                                for(String ignoreName : ignoreNameList) {
                                    if(nick.contains(ignoreName)){
                                        //匹配到了过滤标签，则不发送消息
                                        sendMsgFlag = false;
                                        break;
                                    }
                                }
                            }

                            //如果昵称没有成功匹配过滤，则再匹配备注过滤，如果昵称已经匹配过滤成功了，则无需再匹配备注
                            if(sendMsgFlag){
                                if(IgnoreRemarkListFlag) {//需要过滤昵称
                                    String remark = Tools.getStr(esWorkWxContacts.getRemark());
                                    for(String ignoreRemark : ignoreRemarkList) {
                                        if(remark.contains(ignoreRemark)){
                                            //匹配到了过滤标签，则不发送消息
                                            sendMsgFlag = false;
                                            break;
                                        }
                                    }
                                }
                            }

                            //没有过滤则发送消息
                            if(sendMsgFlag){
                                //调用微服务群发消息
                                NewGroupSendMsgDto newGroupSendMsgDto = new NewGroupSendMsgDto();
                                newGroupSendMsgDto.setParentJobId(groupSendJob_son.getParentId());
                                newGroupSendMsgDto.setChildJobId(groupSendJob_son.getId());
                                String msg = Tools.getStr(groupSendJob_son.getContent());
                                msg = msg.replace("[随机表情]",Tools.getStr(EmojiUtil.getRandomEmoji()))
                                        .replace("[昵称]",Tools.getStr(esWorkWxContacts.getUserName()));
                                newGroupSendMsgDto.setMsg(msg);

                                newGroupSendMsgDto.setMerId(esWorkWxContacts.getMerId());
                                newGroupSendMsgDto.setDeviceUniqueId(esWorkWxContacts.getDeviceUniqueId());
                                newGroupSendMsgDto.setDeviceType(deviceWxworkInfo.getRecvmsgType());
                                newGroupSendMsgDto.setDeviceId(deviceWxworkInfo.getDeviceId());
                                newGroupSendMsgDto.setMsgType(MessageTypeEnum.MT_TEXT.getValue());
                                newGroupSendMsgDto.setUserId(null);
                                newGroupSendMsgDto.setBizUserId(esWorkWxContacts.getWxid());
                                newGroupSendMsgDto.setNickName(esWorkWxContacts.getUserName());
                                newGroupSendMsgDto.setDelay(delay);
                                newGroupSendMsgDto.setOriginalDelay(delay);
                                //delay = delay + wxworkNewBatchSendMessageTaskDto.getTimeInterval(); //循环累加延迟时间
                                //循环累加延迟时间(从最小和最大之间随机获取间隔时间)
                                //发送间隔最小时间
                                Integer rateMin = Tools.getInteger(wxworkNewBatchSendMessageTaskDto.getTimeIntervalMin());
                                //发送间隔最大时间
                                Integer rateMax = Tools.getInteger(wxworkNewBatchSendMessageTaskDto.getTimeInterval());
                                int random = (int)(Math.random()*(rateMax-rateMin+1)+rateMin);
                                delay = delay + random; //循环累加延迟时间
                                newGroupSendMsgDto.setRetry(0);
                                newGroupSendMsgDto.setLabel(Tools.getStrNull(JSONObject.toJSONString(wxworkNewBatchSendMessageTaskDto.getUserLabList())));
                                //会员标签
                                newGroupSendMsgDto.setUserTags(Tools.getStrNull(JSONObject.toJSONString(wxworkNewBatchSendMessageTaskDto.getUserTagsList())));
                                String userRemark = Tools.getStr(wxworkNewBatchSendMessageTaskDto.getUserRemark());
                                userRemark = userRemark.replace("[昵称]",Tools.getStr(esWorkWxContacts.getUserName()))
                                        .replace("[群发时间]", Tools.getDateFormat(new Date(), "yyMMdd"));
                                newGroupSendMsgDto.setRemark(userRemark);
                                newGroupSendMsgDtoList.add(newGroupSendMsgDto);
                            }
                        }
                    }

                    //调用微服务批量发送消息
                    if(newGroupSendMsgDtoList.size() > 0){
                        UzaiRespVo<Boolean>  uzaiRespVo = uzaiBroadcastFeignService.groupSendMsgPush(newGroupSendMsgDtoList);
                        if(uzaiRespVo != null && uzaiRespVo.getCode() == 200){
                            //logger.info("----通讯录新建群发消息任务---para={}, size={}. result={}", JSONObject.toJSONString(wxworkContactsQuery), newGroupSendMsgDtoList.size(), JSONObject.toJSONString(uzaiRespVo));
                            //实际发送总数累加
                            sendMsgTotal_real = sendMsgTotal_real + newGroupSendMsgDtoList.size();
                        }else{
                            logger.error("----通讯录新建群发消息任务失败---size={}", newGroupSendMsgDtoList.size());
                            //失败的在调用一次,再次失败则修改群发消息条数
                            UzaiRespVo<Boolean> uzaiRespVo_repeat = uzaiBroadcastFeignService.groupSendMsgPush(newGroupSendMsgDtoList);
                            if(uzaiRespVo_repeat != null && uzaiRespVo_repeat.getCode() == 200) {
                                sendMsgTotal_real = sendMsgTotal_real + newGroupSendMsgDtoList.size();
                            }
                        }
                    }

                    pageCurrent ++ ; //页面+1
                    wxworkContactsQuery.setCurrent(pageCurrent); //修改页面
                    esWorkWxContactsPage = findWxworkContactsListForGroupSendMsg(wxworkContactsQuery);
                }
            }catch (Exception e){
                logger.error("---通讯录群发消息异常---deviceUniqueId={},msg={}", deviceUniqueId, e.getMessage());
            }

            //需要修改子任务发送总数
            //groupSendJob_son.setStatus(GroupSendStatusEnum.NOT_START.getValue());
            groupSendJob_son.setTotalCount(sendMsgTotal_real);
            groupSendJobMapper.updateTotalCountById(groupSendJob_son);

            //推送子任务
            GroupSendChildidPushDto groupSendChildidPushDto = new GroupSendChildidPushDto();
            groupSendChildidPushDto.setChildJobId(groupSendJob_son.getId());
            groupSendChildidPushDto.setTimeInterval(groupSendJob_son.getTimeInterval() != null ? groupSendJob_son.getTimeInterval() : 1800); //如果此任务的间隔时间为空，则默认设置为半个小时
            UzaiRespVo<Boolean> uzaiRespVo = uzaiBroadcastFeignService.groupSendChildIdPush(groupSendChildidPushDto);
            logger.info("推送群发消息子任务,dto={}, result={}", JSONObject.toJSONString(groupSendChildidPushDto), JSONObject.toJSONString(uzaiRespVo));
        }

        return sendMsgTotal_real;
    }

    /**
     * 查询根据单个机器人新建群发消息总数
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param wxworkNewBatchSendMessageTaskDto
     * @return null
     */
    public int findBatchSendMessageTaskSyncCount(WxworkNewBatchSendMessageTaskDto wxworkNewBatchSendMessageTaskDto, Long deviceUniqueId){

        //记录发送消息总数
        int sendMsgTotal_real = 0;

        WxworkContactsQuery wxworkContactsQuery = new WxworkContactsQuery();
        wxworkContactsQuery.setMerId(wxworkNewBatchSendMessageTaskDto.getMerId());
        wxworkContactsQuery.setDeviceUniqueId(deviceUniqueId);//单个机器人
        wxworkContactsQuery.setSubDeviceUniqueIdList(wxworkNewBatchSendMessageTaskDto.getSubDeviceUniqueIdList());

        //免打扰时间
        Integer busyTimeInterval = wxworkNewBatchSendMessageTaskDto.getBusyTimeInterval();
        //页面设置了免打扰时间(页面填写的是天数)
        if(busyTimeInterval != null){
            //免骚扰时间(针对群发消息用户过滤，这个时间发以后已经群发消息的用户不查询出来)= 现在时间-页面设置的免打扰时间
            Integer busyGroupSendMsgTime = wxworkNewBatchSendMessageTaskDto.getBeginTime() - busyTimeInterval * 3600 ;
            wxworkContactsQuery.setBusyGroupSendMsgTime(busyGroupSendMsgTime);
        }

        //是否有屏蔽昵称关键词
        boolean IgnoreNameListFlag = false;
        List<String> ignoreNameList = wxworkNewBatchSendMessageTaskDto.getIgnoreNameList();
        if(ignoreNameList != null && ignoreNameList.size() > 0){
            IgnoreNameListFlag = true;
        }

        //是否有屏蔽备注关键词
        boolean IgnoreRemarkListFlag = false;
        List<String> ignoreRemarkList = wxworkNewBatchSendMessageTaskDto.getIgnoreRemarkList();
        if(ignoreRemarkList != null && ignoreRemarkList.size() > 0){
            IgnoreRemarkListFlag = true;
        }


        //查询总用户数
        int pageCurrent = 1; //从第一页开始查询
        wxworkContactsQuery.setCurrent(pageCurrent);
        wxworkContactsQuery.setSize(10);

        Page<EsWorkWxContacts> esWorkWxContactsPage = findWxworkContactsListForGroupSendMsg(wxworkContactsQuery);
        if(esWorkWxContactsPage != null && esWorkWxContactsPage.getRecords() != null && esWorkWxContactsPage.getRecords().size() > 0){
            try {
                while(esWorkWxContactsPage != null && esWorkWxContactsPage.getRecords() != null && esWorkWxContactsPage.getRecords().size() > 0) {
                    List<EsWorkWxContacts> esWorkWxContactsList = esWorkWxContactsPage.getRecords();
                    if(esWorkWxContactsList != null && esWorkWxContactsList.size() > 0){
                        //判断是否先需要匹配查询条件(1-发送前先筛选条件后创建任务)
                        if(Tools.getInteger(wxworkNewBatchSendMessageTaskDto.getParaQueryType()).intValue() == 1){
                            //条件查询过滤，返回符合条件的通讯录
                            esWorkWxContactsList = checkParaQuery(esWorkWxContactsList, wxworkNewBatchSendMessageTaskDto);
                        }

                        for (EsWorkWxContacts esWorkWxContacts : esWorkWxContactsList) {
                            //是否需要发送消息, 默认发送
                            boolean sendMsgFlag = true;

                            if(IgnoreNameListFlag) {//需要过滤昵称
                                String nick = Tools.getStr(esWorkWxContacts.getUserName());
                                for(String ignoreName : ignoreNameList) {
                                    if(nick.contains(ignoreName)){
                                        //匹配到了过滤昵称标签，则不发送消息
                                        sendMsgFlag = false;
                                        break;
                                    }
                                }
                            }

                            //如果昵称没有成功匹配过滤，则再匹配备注过滤，如果昵称已经匹配过滤成功了，则无需再匹配备注
                            if(sendMsgFlag){
                                if(IgnoreRemarkListFlag) {//需要过滤备注
                                    String remark = Tools.getStr(esWorkWxContacts.getRemark());
                                    for(String ignoreRemark : ignoreRemarkList) {
                                        if(remark.contains(ignoreRemark)){
                                            //匹配到了过滤备注标签，则不发送消息
                                            sendMsgFlag = false;
                                            break;
                                        }
                                    }
                                }
                            }
                            if(sendMsgFlag){
                                sendMsgTotal_real++;
                            }
                        }
                    }
                    //调用微服务批量发送消息
                    pageCurrent ++ ; //页面+1
                    wxworkContactsQuery.setCurrent(pageCurrent); //修改页面
                    esWorkWxContactsPage = findWxworkContactsListForGroupSendMsg(wxworkContactsQuery);
                }
            }catch (Exception e){
                logger.error("---通讯录群发消息异常---deviceUniqueId={},msg={}", deviceUniqueId, e.getMessage());
            }
        }

        return sendMsgTotal_real;
    }


    //群发时，判断符合条件的会员列表，符合条件的返回
    private List<EsWorkWxContacts> checkParaQuery(List<EsWorkWxContacts> esWorkWxContactsList, WxworkNewBatchSendMessageTaskDto wxworkNewBatchSendMessageTaskDto){

        //存放符合条件的通讯录
        List<EsWorkWxContacts> esWorkWxContacts_volid = new ArrayList<>();

        if(esWorkWxContactsList == null ){
            return esWorkWxContacts_volid;
        }

        //存放当前页通讯录里查询出的微信id列表
        List<String> wxidList_query = new ArrayList<>();
        for (EsWorkWxContacts esWorkWxContacts : esWorkWxContactsList) {
            wxidList_query.add(esWorkWxContacts.getWxid());
        }

        //获取群发查询条件
        GroupSendJobUserQueryParaDto groupSendJobUserQueryParaDto = wxworkNewBatchSendMessageTaskDto.getGroupSendJobUserQueryParaDto();
        //判断是否有查询条件，如果没有，则不需要查询
        if(groupSendJobUserQueryParaDto != null){
            //1-先验证订单查询条件
            if(!groupSendJobUserQueryParaDto.checkOrderConditionIsAllNull()){
                GroupSendJobConditionOrderDto conditionOrder = new GroupSendJobConditionOrderDto();
                conditionOrder.setCidList(groupSendJobUserQueryParaDto.getCidList());
                conditionOrder.setOrderCreateTimeStart(groupSendJobUserQueryParaDto.getOrderCreateTimeStart());
                conditionOrder.setOrderCreateTimeEnd(groupSendJobUserQueryParaDto.getOrderCreateTimeEnd());
                conditionOrder.setOrderTitleList(groupSendJobUserQueryParaDto.getOrderTitleList());
                conditionOrder.setPlatform(groupSendJobUserQueryParaDto.getPlatform());
                conditionOrder.setBizUserIdList(wxidList_query);
                conditionOrder.setMerId(wxworkNewBatchSendMessageTaskDto.getMerId());
                wxidList_query = groupSendJobConditionService.checkOrderConditionWithUserIds(conditionOrder);
                //判断是否匹配到符合订单条件的会员，如果未查询到，则返回null
                if(wxidList_query == null || wxidList_query.size() == 0){
                    return esWorkWxContacts_volid;
                }
            }

            //2-再验证会员查询条件
            if(!groupSendJobUserQueryParaDto.checkUserConditionIsAllNull()){
                WxworkUserQuery wxworkUserQuery = new WxworkUserQuery();
                wxworkUserQuery.setRegChannelList(groupSendJobUserQueryParaDto.getRegChannelList());
                wxworkUserQuery.setRegTimeStart(groupSendJobUserQueryParaDto.getRegTimeStart());
                wxworkUserQuery.setRegTimeEnd(groupSendJobUserQueryParaDto.getRegTimeEnd());
                wxworkUserQuery.setTbLastOrderNo(groupSendJobUserQueryParaDto.getTbLastOrderNo());
                wxworkUserQuery.setLastOrderTimeStart(groupSendJobUserQueryParaDto.getLastOrderTimeStart());
                wxworkUserQuery.setLastOrderTimeEnd(groupSendJobUserQueryParaDto.getLastOrderTimeEnd());
                wxworkUserQuery.setLastOrderType(groupSendJobUserQueryParaDto.getLastOrderType());
                wxworkUserQuery.setLastOrderTypeTime(groupSendJobUserQueryParaDto.getLastOrderTypeTime());
                wxworkUserQuery.setUserTypeList(groupSendJobUserQueryParaDto.getUserTypeList());
                wxworkUserQuery.setGender(groupSendJobUserQueryParaDto.getGender());
                wxworkUserQuery.setRemarkList(groupSendJobUserQueryParaDto.getRemarkList());
                wxworkUserQuery.setRemarkNullFlag(groupSendJobUserQueryParaDto.getRemarkNullFlag());
                wxworkUserQuery.setRemarkExcludeList(groupSendJobUserQueryParaDto.getRemarkExcludeList());
                wxworkUserQuery.setNameList(groupSendJobUserQueryParaDto.getNameList());
                wxworkUserQuery.setNameNullFlag(groupSendJobUserQueryParaDto.getNameNullFlag());
                wxworkUserQuery.setNameExcludeList(groupSendJobUserQueryParaDto.getNameExcludeList());
                wxworkUserQuery.setTagsList(groupSendJobUserQueryParaDto.getTagsList());
                wxworkUserQuery.setTagsNullFlag(groupSendJobUserQueryParaDto.getTagsNullFlag());
                wxworkUserQuery.setTagsExcludeList(groupSendJobUserQueryParaDto.getTagsExcludeList());
                wxworkUserQuery.setSysTagsList(groupSendJobUserQueryParaDto.getSysTagsList());
                wxworkUserQuery.setSysTagsNullFlag(groupSendJobUserQueryParaDto.getSysTagsNullFlag());
                wxworkUserQuery.setSysTagsExcludeList(groupSendJobUserQueryParaDto.getSysTagsExcludeList());
                wxworkUserQuery.setMinBalance(groupSendJobUserQueryParaDto.getMinBalance());
                wxworkUserQuery.setMaxBalance(groupSendJobUserQueryParaDto.getMaxBalance());
                wxworkUserQuery.setMinIntegral(groupSendJobUserQueryParaDto.getMinIntegral());
                wxworkUserQuery.setMaxIntegral(groupSendJobUserQueryParaDto.getMaxIntegral());
                wxworkUserQuery.setMerId(wxworkNewBatchSendMessageTaskDto.getMerId());
                wxworkUserQuery.setWxidList(wxidList_query);
                List<WxworkUser> wxworkUserList = wxworkUserMapper.findByList(wxworkUserQuery);
                //未找到符合条件会员，则返回空
                if(wxworkUserList == null || wxworkUserList.size() == 0){
                    return esWorkWxContacts_volid;
                }
                //找到了符合条件的微信wxid，找出来封装成列表返回
                wxidList_query = wxworkUserList.stream().map(WxworkUser::getWxid).collect(Collectors.toList());
            }

            //循环查询符合条件的通讯录
            for (String wxid : wxidList_query) {
                for (EsWorkWxContacts esWorkWxContacts : esWorkWxContactsList) {
                    if(wxid.equals(esWorkWxContacts.getWxid())){
                        esWorkWxContacts_volid.add(esWorkWxContacts);
                        break;
                    }
                }
            }
        }

        return esWorkWxContacts_volid;
    }


    /**
     * 导出记录数和总金额
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param wxworkContactsQuery
     */
    public ExportAmountVo getExportAmount(WxworkContactsQuery wxworkContactsQuery){

        if(wxworkContactsQuery.getDeviceUniqueIdList() == null && wxworkContactsQuery.getDeviceUniqueIdList().size() == 0){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择机器人");
        }

        //单个机器人查询总数
        long totalCount = searchTotal(wxworkContactsQuery);
        if(totalCount == 0){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "查询结果记录数为0");
        }

        if(totalCount >= ESConstant.TOTAL_MAX) { //大于1万条，不支持导出
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "查询结果总数超过1万条");
        }

        String price = sysConfigMapper.selectByKey("export_record_price");

        ExportAmountVo  exportAmountVo = new ExportAmountVo();
        exportAmountVo.setAmountTotal(1.00);
        exportAmountVo.setCountTotal(totalCount);
        exportAmountVo.setPrice(Double.parseDouble(price));

        return exportAmountVo;

    }

    /**
     * 批量同步微信备注到用户列表
     * @author liuqi
     * @date 2021/8/13 11:38
     * @return null
     */
    @Async("taskExecutor")
    public void batchRefreshUserRemark(WxworkContactsBatchRefreshUserRemarkDto wxworkContactsBatchRefreshUserRemarkDto){
        //查询通讯录
        int currentPage = 1; //当前页
        int size = 20;
        //查询总用户数
        WxworkContactsQuery wxworkContactsQuery = new WxworkContactsQuery();
        wxworkContactsQuery.setMerId(wxworkContactsBatchRefreshUserRemarkDto.getMerId());
        wxworkContactsQuery.setDeviceUniqueId(wxworkContactsBatchRefreshUserRemarkDto.getDeviceUniqueId());
        wxworkContactsQuery.setSize(size);
        wxworkContactsQuery.setCurrent(currentPage);

        Page<WxworkContactsVo> wxworkContactsVoPage = findWxworkContactsList(wxworkContactsQuery, false);
        while(wxworkContactsVoPage != null && wxworkContactsVoPage.getRecords() != null && wxworkContactsVoPage.getRecords().size() > 0){
            //发送消息
            for(WxworkContactsVo wxworkContactsVo : wxworkContactsVoPage.getRecords()){
                try {
                    //会员信息
                    if(wxworkContactsVo.getUserId() != null){
                        WxworkUser wxworkUser = wxworkUserMapper.selectById(wxworkContactsVo.getUserId(), wxworkContactsVo.getMerId());
                        if(wxworkUser != null){ //找到会员信息，才更新备注
                            wxworkUser.setRemark(wxworkContactsVo.getRemark());
                            wxworkUserMapper.updateRemarkAndTags(wxworkUser);
                        }
                    }
                }catch (Exception e){
                    logger.error("修改会员备注失败，error={}", e.getMessage());
                }
            }

            currentPage ++ ; //页码+1
            wxworkContactsQuery.setCurrent(currentPage);
            wxworkContactsVoPage = findWxworkContactsList(wxworkContactsQuery, false);
        }
    }

    /**
     * 删除单个机器人的通讯录
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param merId
     * @return null
     */
    public void deleteWxContactsByDeviceUniqueId(Long deviceUniqueId, Long merId){
        DeleteByQueryRequest deleteByQueryRequest = new DeleteByQueryRequest();
        //清空所有的发送明细
        SearchSourceBuilder searchSourceBuilder_del = new SearchSourceBuilder();
        BoolQueryBuilder boolQuery_and = new BoolQueryBuilder();
        //运营商ID
        boolQuery_and.must(QueryBuilders.termQuery("merId", merId));
        //机器人唯一id
        boolQuery_and.must(QueryBuilders.termQuery("deviceUniqueId", deviceUniqueId));
        searchSourceBuilder_del.query(boolQuery_and).size(100);
        deleteByQueryRequest.getSearchRequest().source(searchSourceBuilder_del);
        String uzai_workwx_contacts = EsIndexName.UZAI_WORKWX_CONTACTS;
        elasticsearchUtilGroupMsg.deleteDataByQueryMulti(uzai_workwx_contacts, deleteByQueryRequest);
    }

    /**
     * 通讯录批量删除
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param wxworkContactsQuery
     * @return null
     */
    public void batchDeleteSync(WxworkContactsQuery wxworkContactsQuery){
        DeleteByQueryRequest deleteByQueryRequest = new DeleteByQueryRequest();
        //清空所有的发送明细
        SearchSourceBuilder searchSourceBuilder_del = new SearchSourceBuilder();

        BoolQueryBuilder boolQuery_and = QueryBuilders.boolQuery();
        BoolQueryBuilder boolQuery_or = QueryBuilders.boolQuery();

        //运营商ID
        boolQuery_and.must(QueryBuilders.termQuery("merId", Tools.getLong(wxworkContactsQuery.getMerId())));

        //性别
        if(wxworkContactsQuery.getGender() != null){
            boolQuery_and.must(QueryBuilders.termQuery("gender", wxworkContactsQuery.getGender()));
        }

        //高亮字段
        String highlightField = null;

        //微信昵称
        if(StringUtils.isNotBlank(wxworkContactsQuery.getUserName())){
            boolQuery_or.should(QueryBuilders.matchQuery("userName", wxworkContactsQuery.getUserName()));
            boolQuery_or.should(QueryBuilders.termQuery("userName.raw", wxworkContactsQuery.getUserName()));
            //highlightField = "userName";
        }

        //微信id
        if(StringUtils.isNotBlank(wxworkContactsQuery.getWxid())){
            boolQuery_and.must(QueryBuilders.termQuery("wxid",wxworkContactsQuery.getWxid()));
            //highlightField = "wxid";
        }

        //机器人唯一ID
        if(wxworkContactsQuery.getDeviceUniqueId() != null){
            boolQuery_and.must(QueryBuilders.termQuery("deviceUniqueId",wxworkContactsQuery.getDeviceUniqueId()));
        }

        //机器人唯一id列表
        if(wxworkContactsQuery.getDeviceUniqueIdList() != null && wxworkContactsQuery.getDeviceUniqueIdList().size() > 0){
            boolQuery_and.must(QueryBuilders.termsQuery("deviceUniqueId", wxworkContactsQuery.getDeviceUniqueIdList()));
        }

        //子账号绑定机器人
        List<Long> subDeviceUniqueIdList = wxworkContactsQuery.getSubDeviceUniqueIdList();
        if(subDeviceUniqueIdList != null && subDeviceUniqueIdList.size() > 0){
            for (Long deviceUniqueId : subDeviceUniqueIdList) {
                boolQuery_or.should(QueryBuilders.termQuery("deviceUniqueId", deviceUniqueId));
            }
        }

        //最后群发消息开始时间
        if(wxworkContactsQuery.getLastGroupSendTimeStart() != null){
            boolQuery_and.must(QueryBuilders.rangeQuery("lastGroupSendTime").gte(wxworkContactsQuery.getLastGroupSendTimeStart()));
        }

        //最后群发消息结束时间
        if(wxworkContactsQuery.getLastGroupSendTimeEnd() != null){
            boolQuery_and.must(QueryBuilders.rangeQuery("lastGroupSendTime").lte(wxworkContactsQuery.getLastGroupSendTimeEnd()));
        }

        //免骚扰时间(针对群发消息用户过滤，这个时间发以后已经群发消息的用户不查询出来)
        if(wxworkContactsQuery.getBusyGroupSendMsgTime() != null){
            boolQuery_and.must(QueryBuilders.rangeQuery("lastGroupSendTime").lt(wxworkContactsQuery.getBusyGroupSendMsgTime()));
        }

        searchSourceBuilder_del.query(boolQuery_and.must(boolQuery_or)).size(100);
        deleteByQueryRequest.getSearchRequest().source(searchSourceBuilder_del);
        String uzai_workwx_contacts = EsIndexName.UZAI_WORKWX_CONTACTS;
        elasticsearchUtilGroupMsg.deleteDataByQueryMulti(uzai_workwx_contacts, deleteByQueryRequest);
    }

}
